home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / The World of Computer Software.iso / snpd1292.zip / SPLIT.C < prev    next >
C/C++ Source or Header  |  1992-12-26  |  2KB  |  78 lines

  1. /*
  2. **  split() - Portable replacement for fnsplit(), _splitpath(), etc.
  3. **
  4. **  Splits a full DOS pathname into path, file, and extension specifications.
  5. **  Works with forward or back slash path separators and network
  6. **  file names, e.g. NET:LOONEY/BIN\WUMPUS.COM, Z:\MYDIR.NEW/NAME.EXT
  7. **
  8. **  Arguments: 1 - Full pathname to split
  9. **             2 - Buffer for path
  10. **             3 - Buffer for name
  11. **             4 - Buffer for extension
  12. **
  13. **  Returns: Nothing
  14. */
  15.  
  16. #include <string.h>
  17.  
  18. #define NUL '\0'
  19.  
  20. void split(char *filepath, char *pathname, char *fname, char *ext)
  21. {
  22.       char ch, *ptr, *p;
  23.  
  24.       /* convert slashes to backslashes for searching         */
  25.  
  26.       for (ptr = filepath; *ptr; ++ptr)
  27.             if ('/' == *ptr)
  28.                   *ptr = '\\';
  29.  
  30.       /* find rightmost backslash or leftmost colon           */
  31.  
  32.       if (NULL == (ptr = strrchr(filepath, '\\')))
  33.             ptr = (strchr(filepath, ':'));
  34.  
  35.       if (!ptr)
  36.       {
  37.             ptr = filepath;         /* obviously, no path   */
  38.             *pathname = NUL;
  39.       }
  40.       else
  41.       {
  42.             ++ptr;                  /* skip the delimiter   */
  43.             ch = *ptr;
  44.             *ptr = NUL;
  45.             strcpy(pathname, filepath);
  46.             *ptr = ch;
  47.       }
  48.  
  49.       if (NULL == (p = strrchr(ptr, '.')))
  50.       {
  51.             strcpy(fname, ptr);
  52.             *ext = NUL;
  53.       }
  54.       else
  55.       {
  56.             *p = NUL;
  57.             strcpy(fname, ptr);
  58.             *p = '.';
  59.             strcpy(ext, p);
  60.       }
  61. }
  62.  
  63. #ifdef TEST
  64.  
  65. #include <stdio.h>
  66.  
  67. int main(int argc, char *argv[])
  68. {
  69.       char pathname[FILENAME_MAX], fname[9], ext[5];
  70.  
  71.       while (--argc)
  72.       {
  73.             split(*++argv, pathname, fname, ext);
  74.             printf("split(%s) returns:\n path = %s\n name = %s\n ext  = %s\n",
  75.                   *argv, pathname, fname, ext);
  76.       }
  77. }
  78.